#include "widget.h"


Widget::Widget()
{


    setWindowTitle("温控系统主界面");
    this->resize(1050,600);
    QVBoxLayout *vbox =new QVBoxLayout(this);
    QHBoxLayout *hbox =new QHBoxLayout();
    table =new QTableWidget;
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setEditTriggers(QAbstractItemView::CurrentChanged);
    table->setColumnCount(7);
    table->setHorizontalHeaderLabels(QStringList()<<"名称"<<"所在地"<<"温度"<<"湿度"<<"状态"<<"空调温度"<<"详情");
    vbox->addWidget(table,9);
    vbox->addLayout(hbox,1);

    add =new QPushButton("添加基站");
    del =new QPushButton("删除基站");
    jing_diary =new QPushButton("报警日志");
    update =new QPushButton("刷新");
    baojing = new jing;
    hbox->addWidget(add);
    hbox->addWidget(del);
    hbox->addWidget(jing_diary);
    hbox->addWidget(update);
    connect(add,&QPushButton::clicked,this,&Widget::addbasic);
    connect(jing_diary,&QPushButton::clicked,this,&Widget::jingbasic);
    connect(del,&QPushButton::clicked,this,&Widget::deletebasic);
    connect(update,&QPushButton::clicked,this,&Widget::flushtable);
    connect(table,&QTableWidget::cellChanged,this,&Widget::Tablechange);


    client = new QMQTT::Client(QHostAddress("127.0.0.1"),1883);
    client->setClientId("mqttx_05674e11");
    client->setUsername("1231");
    client->setPassword("123");
    on_pb_connect_clicked();
    connect(client,SIGNAL(received(QMQTT::Message)),this,SLOT(doDataReceived(QMQTT::Message)));

}


void Widget::addmess()
{
    disconnect(table,&QTableWidget::cellChanged,0,0);
    QString name=addjizhan->getname(),address=addjizhan->getaddress();
    xx.push_back(NULL);
    xx[++count] = new QPushButton("详情");
    int irow =table->rowCount();
    table->setRowCount(irow+1);
    table->setItem(irow,0,new QTableWidgetItem(name));
    table->setItem(irow,1,new QTableWidgetItem(address));
    table->setItem(irow,2,new QTableWidgetItem(0));
    table->setItem(irow,3,new QTableWidgetItem(0));
    table->setItem(irow,4,new QTableWidgetItem(0));
    table->setItem(irow,5,new QTableWidgetItem(0));
    table->setCellWidget(irow,6,xx[count]);
    for(int i=0;i<5;i++)
    {
        item = table->item(irow,i);
        item->setFlags(Qt::ItemIsEnabled);//设置改item不可修改；
    }
    client->subscribe(name.trimmed());
    chi[name] = new child;
    connect(xx[count],&QPushButton::clicked,this,&Widget::openchild);
    connect(table,&QTableWidget::cellChanged,this,&Widget::Tablechange);
}

void Widget::addbasic()
{
    addjizhan = new Add;
    QObject::connect(addjizhan,&Add::closeBox,this,&Widget::addmess);
    addjizhan->show();
}

void Widget::jingbasic()
{
    baojing->show();
}

void Widget::openchild()
{
    for(int i=0;i<xx.size();i++)
    {
        if(xx[i]->hasFocus())
        {
            qDebug()<<table->item(i,0)->text();
            chi[table->item(i,0)->text()]->show();
            break ;
        }
    }
}


void Widget::deletebasic()
{

    int rowIndex = table->currentRow();
    if (rowIndex != -1)
     {
        QList<QTableWidgetItem*>items =table->selectedItems();
        QMessageBox::StandardButton result=QMessageBox::question(this,"删除","确定要删除该基站吗？");
        if(result == QMessageBox::Yes)
        {

            QString name,addr;
            QFile file("basic.txt");
            file.open(QIODevice::ReadOnly);
            QDataStream read(&file);
            QFile file1("1.txt");
            file1.open(QIODevice::WriteOnly);
            QDataStream write(&file1);
           while(!read.atEnd())
           {
               read >> name >> addr;
               if(name!=table->item(rowIndex,0)->text()) write<<name<<addr;

               else client->unsubscribe(name);
           }
           file.close();
           file1.close();
           file.remove();
           file1.rename("basic.txt");
           table->removeRow(rowIndex);
        }
    }

}


void Widget::flushtable()
{

    disconnect(table,&QTableWidget::cellChanged,0,0);
    QFile file("basic.txt");
    file.open(QIODevice::ReadOnly);
    QDataStream  datastr(&file);
    QString name,addr;
    table->setRowCount(0);
    while(!datastr.atEnd())
    {
        xx.push_back(NULL);
        xx[++count] =new QPushButton("详情");
        table->setRowCount(table->rowCount()+1);
        datastr>>name>>addr;
        table->setItem(table->rowCount()-1,0,new QTableWidgetItem(name));
        table->setItem(table->rowCount()-1,1,new QTableWidgetItem(addr));
        table->setItem(table->rowCount()-1,2,new QTableWidgetItem(0));
        table->setItem(table->rowCount()-1,3,new QTableWidgetItem(0));
        table->setItem(table->rowCount()-1,4,new QTableWidgetItem(0));
        table->setItem(table->rowCount()-1,5,new QTableWidgetItem(0));//通过直接从文件读写的方式来更新表格信息
        table->setCellWidget(table->rowCount()-1,6,xx[count]);
        for(int i=0;i<5;i++)
        {
            item = table->item(table->rowCount()-1,i);
            item->setFlags(Qt::ItemIsEnabled);//设置改item不可修改；
        }
        client->subscribe(name.trimmed());
        client->subscribe(name.trimmed() + "_2");
        client->subscribe(name.trimmed() + "_shi");
        chi[name] = new child;qDebug()<<"yunxing";
        connect(xx[count],&QPushButton::clicked,this,&Widget::openchild);
    }
    connect(table,&QTableWidget::cellChanged,this,&Widget::Tablechange);
}

void Widget::on_pb_connect_clicked()
{

    if(!client->isConnectedToHost())
    {
        client->connectToHost();
        qDebug()<<"已连接";
    }
    else {
        client->disconnectFromHost();
        qDebug()<<"未连接";
    }
}

QString Widget::get_last_wen(QString name)
{
    return jizhan[name].last();
}

void Widget::doDataReceived(QMQTT::Message message)
{
    if(message.topic().length() > 2 && message.topic().right(2) == "_2"){
        chi[message.topic().left(message.topic().length()-2)]->setvalue2(message.payload());
        return ;
    }//提交数据为室外温度,否则为室内温度

    qDebug() << message.topic().left(message.topic().length());

    jizhan[message.topic()].enqueue(message.payload());
    if(jizhan[message.topic()].size()>50) jizhan[message.topic()].dequeue();
    chi[message.topic()]->setvalue(message.payload());
    int now =0;

    while(now < table->rowCount() )
    {
        if(table->item(now,0)->text()==message.topic())
        {
            table->setItem(now,2,new QTableWidgetItem(jizhan[message.topic()].last()));
            item = table->item(now,2);
            item->setFlags(Qt::ItemIsEnabled);
            int mess = message.payload().toInt();
            if(mess>35 || mess < 0)
            {
                QString level,leixing;
                if(mess<0) {
                    level = "高";
                    leixing = "停电";
                }
                else level = "低",leixing = "温度过高";
                baojing->getdata(table->item(now,0)->text(),table->item(now,1)->text(),table->item(now,2)->text(),"75%",level,leixing);
            }
            break;
        }
        now++;
    }
}


void Widget::Tablechange(int row)
{
    QString topic,payload;
    topic = table->item(row,0)->text();
    payload = table->item(row,5)->text();
    topic += "push";
    qDebug() << topic ;
    QMQTT::Message message(136,topic,payload.toUtf8());

    client->publish(message);
}
